package com.heyu.cgsd.ui.fragment;

import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.heyu.cgsd.R;
import com.heyu.cgsd.util.Arith;
import com.heyu.cgsd.util.CalcUtils2;
import com.heyu.cgsd.util.DisplayUtils;
import com.heyu.cgsd.util.NumberFormatUtils;

public class ScienceFragment extends BaseLazyFragment {
    private int clearCount;// 清除次数
    private String curOperate;
    private String inputStr;
    private String resultStr;
    private String historyStr;

    private TextView tv_calc_history, tv_calc_input, tv_calc_result;

    private TextView kb_num_ac, kb_num_del, kb_num_divide, kb_num_multiply, kb_num_sub, kb_num_add, kb_num_equal, kb_num_percent, kb_num_dot;
    private TextView kb_num_0, kb_num_1, kb_num_2, kb_num_3, kb_num_4, kb_num_5, kb_num_6, kb_num_7, kb_num_8, kb_num_9;

    private TextView kb_num_2nd, kb_num_deg;
    private FrameLayout kb_num_sin, kb_num_cos, kb_num_tan;
    private TextView kb_sin_m1, kb_cos_m1, kb_tan_m1;
    private TextView kb_num_xy, kb_num_lg, kb_num_ln, kb_num_left, kb_num_right;
    private TextView kb_num_x2, kb_num_xx, kb_num_1x, kb_num_pi, kb_num_e;

    private boolean is2nd;
    private boolean isRad;
    private boolean isEqual;

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_science;
    }

    @Override
    protected void initViews(View view) {
        tv_calc_history = view.findViewById(R.id.tv_calc_history);
        tv_calc_input = view.findViewById(R.id.tv_calc_input);
        tv_calc_result = view.findViewById(R.id.tv_calc_result);

        kb_num_ac = view.findViewById(R.id.kb_num_ac);
        kb_num_del = view.findViewById(R.id.kb_num_del);
        kb_num_divide = view.findViewById(R.id.kb_num_divide);
        kb_num_multiply = view.findViewById(R.id.kb_num_multiply);
        kb_num_sub = view.findViewById(R.id.kb_num_sub);
        kb_num_add = view.findViewById(R.id.kb_num_add);
        kb_num_equal = view.findViewById(R.id.kb_num_equal);
        kb_num_percent = view.findViewById(R.id.kb_num_percent);
        kb_num_dot = view.findViewById(R.id.kb_num_dot);
        kb_num_0 = view.findViewById(R.id.kb_num_0);
        kb_num_1 = view.findViewById(R.id.kb_num_1);
        kb_num_2 = view.findViewById(R.id.kb_num_2);
        kb_num_3 = view.findViewById(R.id.kb_num_3);
        kb_num_4 = view.findViewById(R.id.kb_num_4);
        kb_num_5 = view.findViewById(R.id.kb_num_5);
        kb_num_6 = view.findViewById(R.id.kb_num_6);
        kb_num_7 = view.findViewById(R.id.kb_num_7);
        kb_num_8 = view.findViewById(R.id.kb_num_8);
        kb_num_9 = view.findViewById(R.id.kb_num_9);

        kb_num_2nd = view.findViewById(R.id.kb_num_2nd);
        kb_num_deg = view.findViewById(R.id.kb_num_deg);
        kb_num_sin = view.findViewById(R.id.kb_num_sin);
        kb_num_cos = view.findViewById(R.id.kb_num_cos);
        kb_num_tan = view.findViewById(R.id.kb_num_tan);

        kb_sin_m1 = view.findViewById(R.id.kb_sin_m1);
        kb_cos_m1 = view.findViewById(R.id.kb_cos_m1);
        kb_tan_m1 = view.findViewById(R.id.kb_tan_m1);

        kb_num_xy = view.findViewById(R.id.kb_num_xy);
        kb_num_lg = view.findViewById(R.id.kb_num_lg);
        kb_num_ln = view.findViewById(R.id.kb_num_ln);
        kb_num_left = view.findViewById(R.id.kb_num_left);
        kb_num_right = view.findViewById(R.id.kb_num_right);

        kb_num_x2 = view.findViewById(R.id.kb_num_x2);
        kb_num_xx = view.findViewById(R.id.kb_num_xx);
        kb_num_1x = view.findViewById(R.id.kb_num_1x);
        kb_num_pi = view.findViewById(R.id.kb_num_pi);
        kb_num_e = view.findViewById(R.id.kb_num_e);
    }

    @Override
    protected void initData() {
        clearCount = 0;
        is2nd = false;
        isRad = false;
        isEqual = false;
        inputStr = "0";
        resultStr = "";
        historyStr = "";
        curOperate = "";

        kb_sin_m1.setVisibility(View.GONE);
        kb_cos_m1.setVisibility(View.GONE);
        kb_tan_m1.setVisibility(View.GONE);

        tv_calc_history.setText("");
        tv_calc_input.setText("0");
        tv_calc_result.setText("");
    }

    @Override
    protected void initListener() {
        setNormalKeyBoardListener();
        setScienceKeyBoardListener();
    }

    private void setNormalKeyBoardListener() {
        kb_num_0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("0", false);
            }
        });

        kb_num_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("1", false);
            }
        });

        kb_num_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("2", false);
            }
        });

        kb_num_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("3", false);
            }
        });

        kb_num_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("4", false);
            }
        });

        kb_num_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("5", false);
            }
        });

        kb_num_6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("6", false);
            }
        });

        kb_num_7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("7", false);
            }
        });

        kb_num_8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("8", false);
            }
        });

        kb_num_9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("9", false);
            }
        });

        kb_num_dot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput(".", false);
            }
        });

        kb_num_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEqual) {
                    if (inputStr.length() > 1) {
                        inputStr = inputStr.substring(0, inputStr.length() - 1);
                        curOperate = "";
                        String last = inputStr.substring(inputStr.length() - 1);
                        if ("E".equals(last)) {
                            inputStr = inputStr.substring(0, inputStr.length() - 1);
                        }
                        if ("＋".equals(last) || "－".equals(last) || "×".equals(last) || "÷".equals(last)) {
                            curOperate = last;
                        }
                        if ("(".equals(last)) {
                            inputStr = inputStr.substring(0, inputStr.length() - 1);
                            if (inputStr.length() > 0) {
                                inputStr = delFront(inputStr);
                            }
                        } else if ("^".equals(last) || "√".equals(last) || "n".equals(last) || "g".equals(last) || "r".equals(last) || "s".equals(last)) {
                            inputStr = delFront(inputStr);
                        }
                    } else {
                        inputStr = "0";
                        curOperate = "";
                    }
                    if ("".equals(inputStr)) {
                        inputStr = "0";
                        curOperate = "";
                    }
                    if ("".equals(curOperate)) {
                        calc();
                    }
                    updateInput();
                }
            }
        });

        kb_num_ac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearInput();
            }
        });

        kb_num_percent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                normalKeyboardInput("%", false);
            }
        });

        kb_num_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEqual = true;
                setLargerFontSize(0);
                clearCount = 0;
            }
        });

        kb_num_divide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"÷".equals(curOperate)) {
                    normalKeyboardInput("÷", true);
                }
            }
        });

        kb_num_multiply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"×".equals(curOperate)) {
                    normalKeyboardInput("×", true);
                }
            }
        });

        kb_num_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"－".equals(curOperate)) {
                    normalKeyboardInput("－", true);
                }
            }
        });

        kb_num_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"＋".equals(curOperate)) {
                    normalKeyboardInput("＋", true);
                }
            }
        });
    }

    private String delFront(String inputStr) {
        String last1 = inputStr.substring(inputStr.length() - 1);
        if ("^".equals(last1) || "√".equals(last1)) {
            inputStr = inputStr.substring(0, inputStr.length() - 1);
        } else {
            if (inputStr.contains("lg") && inputStr.lastIndexOf("lg") == inputStr.length() - 2) {
                inputStr = inputStr.substring(0, inputStr.length() - 2);
            } else if (inputStr.contains("ln") && inputStr.lastIndexOf("ln") == inputStr.length() - 2) {
                inputStr = inputStr.substring(0, inputStr.length() - 2);
            } else if (inputStr.contains("arcsin") && inputStr.lastIndexOf("arcsin") == inputStr.length() - 6) {
                inputStr = inputStr.substring(0, inputStr.length() - 6);
            } else if (inputStr.contains("arccos") && inputStr.lastIndexOf("arccos") == inputStr.length() - 6) {
                inputStr = inputStr.substring(0, inputStr.length() - 6);
            } else if (inputStr.contains("arctan") && inputStr.lastIndexOf("arctan") == inputStr.length() - 6) {
                inputStr = inputStr.substring(0, inputStr.length() - 6);
            } else if (inputStr.contains("sinr") && inputStr.lastIndexOf("sinr") == inputStr.length() - 4) {
                inputStr = inputStr.substring(0, inputStr.length() - 4);
            } else if (inputStr.contains("cosr") && inputStr.lastIndexOf("cosr") == inputStr.length() - 4) {
                inputStr = inputStr.substring(0, inputStr.length() - 4);
            } else if (inputStr.contains("tanr") && inputStr.lastIndexOf("tanr") == inputStr.length() - 4) {
                inputStr = inputStr.substring(0, inputStr.length() - 4);
            } else if (inputStr.contains("sin") && inputStr.lastIndexOf("sin") == inputStr.length() - 3) {
                inputStr = inputStr.substring(0, inputStr.length() - 3);
            } else if (inputStr.contains("cos") && inputStr.lastIndexOf("cos") == inputStr.length() - 3) {
                inputStr = inputStr.substring(0, inputStr.length() - 3);
            } else if (inputStr.contains("tan") && inputStr.lastIndexOf("tan") == inputStr.length() - 3) {
                inputStr = inputStr.substring(0, inputStr.length() - 3);
            }
        }
        return inputStr;
    }

    private void setScienceKeyBoardListener() {
        kb_num_2nd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                is2nd = !is2nd;
                if (is2nd) {
                    kb_num_deg.setEnabled(false);
                    kb_sin_m1.setVisibility(View.VISIBLE);
                    kb_cos_m1.setVisibility(View.VISIBLE);
                    kb_tan_m1.setVisibility(View.VISIBLE);
                } else {
                    kb_num_deg.setEnabled(true);
                    kb_sin_m1.setVisibility(View.GONE);
                    kb_cos_m1.setVisibility(View.GONE);
                    kb_tan_m1.setVisibility(View.GONE);
                }
            }
        });

        kb_num_deg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRad = !isRad;
                if (isRad) {
                    kb_num_deg.setText(getString(R.string.str_rad));
                    kb_num_2nd.setEnabled(false);
                } else {
                    kb_num_deg.setText(getString(R.string.str_deg));
                    kb_num_2nd.setEnabled(true);
                }
            }
        });

        kb_num_sin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRad) {
                    scienceKeyboardInput("sinr(");
                } else if (!is2nd) {
                    scienceKeyboardInput("sin(");
                } else {
                    scienceKeyboardInput("arcsin(");
                }
            }
        });

        kb_num_cos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRad) {
                    scienceKeyboardInput("cosr(");
                } else if (!is2nd) {
                    scienceKeyboardInput("cos(");
                } else {
                    scienceKeyboardInput("arccos(");
                }
            }
        });

        kb_num_tan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRad) {
                    scienceKeyboardInput("tanr(");
                } else if (!is2nd) {
                    scienceKeyboardInput("tan(");
                } else {
                    scienceKeyboardInput("arctan(");
                }
            }
        });

        kb_num_xy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("^");
            }
        });

        kb_num_lg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("lg(");
            }
        });

        kb_num_ln.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("ln(");
            }
        });

        kb_num_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("(");
            }
        });

        kb_num_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput(")");
            }
        });

        kb_num_x2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("√");
            }
        });

        kb_num_xx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("!");
            }
        });

        kb_num_1x.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("^(-1)");
            }
        });

        kb_num_pi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("π");
            }
        });

        kb_num_e.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scienceKeyboardInput("e");
            }
        });
    }

    private void normalKeyboardInput(String input, boolean isOperate) {
        if (isEqual) {
            historyStr = inputStr + "=" + resultStr;
            clearInput();
            if (isOperate) {
                inputStr = resultStr + input;
                curOperate = input;
            } else {
                inputStr = input;
                calc();
            }
            updateHistory();
        } else {
            if (isOperate) {
                if ("".equals(curOperate)) {
                    inputStr += input;
                } else {
                    String tmp = inputStr.substring(inputStr.length() - 1);
                    if ("＋".equals(tmp) || "－".equals(tmp) || "×".equals(tmp) || "÷".equals(tmp)) {
                        inputStr = inputStr.substring(0, inputStr.length() - 1) + input;
                    } else {
                        inputStr += input;
                    }
                }
                curOperate = input;
            } else {
                if ("%".equals(input)) {
                    String part1 = inputStr.substring(inputStr.length() - 1);
                    if ("^".equals(part1) || "√".equals(part1) || "!".equals(part1) || "(".equals(part1) || ")".equals(part1)) {
                        // 不输入
                        return;
                    } else if (!"0".equals(inputStr)) {
                        int len = inputStr.length();
                        int index = 0;
                        StringBuilder sb = new StringBuilder();
                        for (int i = len - 1; i >= 0; i--) {
                            char x = inputStr.charAt(i);
                            if (x == '-' && i > 0) {
                                char y = inputStr.charAt(i - 1);
                                if (y != 'E') {
                                    index = i;
                                    break;
                                }
                            } else if ((x < '0' || x > '9') && x != '.' && x != 'E') {
                                index = i;
                                break;
                            }
                            sb.append(x);
                        }
                        String s = sb.reverse().toString();
                        if (!"".equals(s)) {
                            Double d = Arith.div(Double.valueOf(s), 100d, 326);
                            if (inputStr.contains("r(")) {
                                inputStr = inputStr.substring(0, index + 2) + d;
                            } else {
                                if (index > 0) {
                                    inputStr = inputStr.substring(0, index + 1) + d;
                                } else {
                                    inputStr = inputStr.substring(0, index) + d;
                                }
                            }
                        }
                    }
                } else if (!"0".equals(inputStr)) {
                    inputStr += input;
                } else {
                    if (".".equals(input)) {
                        inputStr = "0" + input;
                    } else {
                        inputStr = input;
                    }
                }
                if (!isRad) {
                    int len = inputStr.length();
                    StringBuilder sb = new StringBuilder();
                    for (int i = len - 1; i >= 0; i--) {
                        char x = inputStr.charAt(i);
                        if (x == ')') {
                            break;
                        }
                        sb.append(x);
                    }
                    String s = sb.reverse().toString();
                    if (s.contains("sin(") || s.contains("cos(") || s.contains("tan(")) {
                        inputStr = inputStr.replaceAll("°", "");
                        inputStr += "°";
                    }
                }
                curOperate = "";
                calc();
            }
        }
        updateInput();
    }

    private void scienceKeyboardInput(String input) {
        if (isEqual) {
            historyStr = inputStr + "=" + resultStr;
            clearInput();
            inputStr = input;
            updateHistory();
        } else {
            if ("".equals(inputStr) || "0".equals(inputStr)) {
                if ("^".equals(input) || "!".equals(input)) {
                    inputStr = "0" + input;
                } else {
                    inputStr = input;
                }
            } else {
                inputStr += input;
            }
            curOperate = input;
        }
        if ("e".equals(input) || "π".equals(input) || "^(-1)".equals(input) || "!".equals(input)) {
            calc();
        }
        updateInput();
    }

    private void calc() {
        String string = CalcUtils2.scienceCalc2(inputStr);
        if (string.contains("出错")) {
            tv_calc_result.setText("出错");
        } else if (string.contains("∞")) {
            tv_calc_result.setText("= ∞");
        } else if (string.contains("不能除以0")) {
            tv_calc_result.setText("= 不能除以0");
        } else {
            if (!string.contains("E")) {
                string = NumberFormatUtils.format2(string);
            }
            resultStr = string;
            if (isRad) {
                resultStr += "°";
            }
            tv_calc_result.setText("= " + resultStr);
        }
    }

    private void clearInput() {
        if (clearCount == 0) {
            clearCount++;
            tv_calc_input.setText("0");
            tv_calc_result.setText("");
        } else {
            tv_calc_history.setText("");
            tv_calc_input.setText("0");
            tv_calc_result.setText("");
        }
        inputStr = "0";
        curOperate = "";
        isEqual = false;
        setLargerFontSize(1);
    }

    private void setLargerFontSize(int type) {
        if (type == 1) {
            tv_calc_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 48));
            tv_calc_result.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 24));
        } else {
            tv_calc_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 24));
            tv_calc_result.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.sp2px(getActivity(), 48));
        }
    }

    private void updateInput() {
        String string = inputStr.replaceAll("sinr", "sin");
        string = string.replaceAll("cosr", "cos");
        string = string.replaceAll("tanr", "tan");

        tv_calc_input.setText(string);
        isEqual = false;
    }

    private void updateHistory() {
        tv_calc_history.setText(historyStr);
    }
}
